package com.yanti.filter;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

// 这个方法没有被迭代，从AddUserId2HeaderFiler上游传导
@Component
@Slf4j
public class AddUserId2HeaderFilter implements Filter {

    private static final String HEADER_USER_ID = "userId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            // 从 Sa-Token 获取当前登录用户 ID（此时 SaServletFilter 已校验登录状态）
            long userId = StpUtil.getLoginIdAsLong();
            log.info("当前用户 ID: {}", userId);

            // 创建包装后的 Request 对象，添加请求头，通过修饰器的方式实现了请求头添加，
            // 实际上是对原始的 Request 对象进行了包装，没有修改原始对象的内容
            HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
                @Override
                public String getHeader(String name) {
                    if (HEADER_USER_ID.equalsIgnoreCase(name)) {
                        return String.valueOf(userId);
                    }
                    return super.getHeader(name);
                }

                @Override
                public Enumeration<String> getHeaders(String name) {
                    if (HEADER_USER_ID.equalsIgnoreCase(name)) {
                        return Collections.enumeration(Collections.singleton(String.valueOf(userId)));
                    }
                    return super.getHeaders(name);
                }

                @Override
                public Enumeration<String> getHeaderNames() {
                    List<String> headerNames = Collections.list(super.getHeaderNames());
                    headerNames.add(HEADER_USER_ID);
                    return Collections.enumeration(headerNames);
                }
            };

            chain.doFilter(wrappedRequest, response);
        } catch (NotLoginException e) {
            // 未登录时直接放行，由 SaServletFilter 处理异常
            chain.doFilter(request, response);
        }
    }
}